﻿namespace AlgLrnLib.Sorting
{
    public class SelectionSort : BaseSort
    {
        #region Public Methods
        public override int[] SortAsc(int[] numbers, DebugTraceDelegate DEBUG_TRACE)
        {
            return Sort(DEBUG_TRACE, numbers);
        }

        public override int[] SortDesc(int[] numbers, DebugTraceDelegate DEBUG_TRACE)
        {
            return Sort(DEBUG_TRACE, numbers, false);
        }
        #endregion

        #region Private Methods
        private int[] Sort(DebugTraceDelegate DEBUG_TRACE, int[] numbers, bool asc = true)
        {
            DEBUG_TRACE(numbers, "INITIAL STATE", true); // Clean the GUI and print initial results

            for (int j = 0; j < numbers.Length; j++)
            {
                int key = j;
                int i = j + 1;
                while (i < numbers.Length)
                {
                    if (numbers[i] < numbers[key])
                        key = i;

                    DEBUG_TRACE(numbers, string.Format("j = {0}, i = {1}, key = {2}, WHILE", j, i, key), false); // Print itteration results to the GUI
                    i++;
                }

                if (Compare(numbers[key], numbers[j], asc))
                {
                    SwapByIndex(numbers, key, j);
                    DEBUG_TRACE(numbers, string.Format("j = {0}, i = {1}, key = {2}, SWAPPED", j, i, key), false); // Print itteration result to the GUI
                }

                DEBUG_TRACE(numbers, string.Format("j = {0}, i = {1}, key = {2}, NOT SWAPPED", j, i, key), false); // Print itteration result to the GUI
            }

            DEBUG_TRACE(numbers, "FINAL STATE", false); // Print final results to the GUI

            return numbers;
        }
        #endregion
    }
}
